package cliente.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.Collection;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

import org.dyno.visual.swing.layouts.Bilateral;
import org.dyno.visual.swing.layouts.Constraints;
import org.dyno.visual.swing.layouts.GroupLayout;
import org.dyno.visual.swing.layouts.Trailing;

import cliente.Cliente;
import cliente.exception.ExceptionCPFInvalido;
import cliente.exception.PessoaNaoEncontradaException;
import fachada.FachadaCliente;

//VS4E -- DO NOT REMOVE THIS LINE!
public class TabelaPesquisaCliente extends JFrame {

        private static final long serialVersionUID = 1L;
        private JButton jButton0;
        private JTable jTable0;
        private JScrollPane jScrollPane0;
        private JButton jButton1;
        private JButton jButton2;
		private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
		
		public TabelaPesquisaCliente() {
                initComponents();
                try {
					listando();
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
        }

        private void initComponents() {
			setResizable(false);
			setLayout(new GroupLayout());
			add(getJButton0(), new Constraints(new Trailing(12, 12, 12), new Trailing(12, 12, 12)));
			add(getJScrollPane0(), new Constraints(new Bilateral(11, 12, 22), new Bilateral(34, 56, 26)));
			add(getJButton2(), new Constraints(new Trailing(178, 237, 237), new Trailing(12, 88, 481)));
			add(getJButton1(), new Constraints(new Trailing(355, 12, 12), new Trailing(12, 88, 481)));
			setSize(620, 400);
		}

		private JButton getJButton2() {
			if (jButton2 == null) {
				jButton2 = new JButton();
				jButton2.setIcon(new ImageIcon(getClass().getResource("/icones/zoom.png")));
				jButton2.setText("Pesquisar Por Nome");
				jButton2.addActionListener(new ActionListener() {
		
					public void actionPerformed(ActionEvent event) {
						jButton2ActionActionPerformed(event);
					}
				});
			}
			return jButton2;
		}

		private JButton getJButton1() {
			if (jButton1 == null) {
				jButton1 = new JButton();
				jButton1.setIcon(new ImageIcon(getClass().getResource("/icones/arrow_refresh.png")));
				jButton1.setText("Atualizar");
				jButton1.addActionListener(new ActionListener() {
		
					public void actionPerformed(ActionEvent event) {
						try {
							jButton1ActionActionPerformed(event);
						} catch (ClassNotFoundException e) {
							System.out.println(e.getMessage());
						} catch (SQLException e) {
							JOptionPane.showMessageDialog(null, "pessoa nao cadastrada");
						}
					}
				});
			}
			return jButton1;
		}

		private JScrollPane getJScrollPane0() {
                if (jScrollPane0 == null) {
                        jScrollPane0 = new JScrollPane();
                        jScrollPane0.setViewportView(getJTable0());
                }
                return jScrollPane0;
        }

        private JTable getJTable0() {
			if (jTable0 == null) {
				jTable0 = new JTable();
				jTable0.setModel(new DefaultTableModel(new Object[][] {
						
				}, new String[] { "nome", "cpf", "identidade", "e-mail", "telefone", "endereco", "numero", "bairro", "cidade", "cep", }) {
					private static final long serialVersionUID = 1L;
					Class<?>[] types = new Class<?>[] { Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class,
							Object.class, Object.class, };
		
					public Class<?> getColumnClass(int columnIndex) {
						return types[columnIndex];
					}
				});
				jTable0.addMouseListener(new MouseAdapter() {
		
					public void mouseClicked(MouseEvent event) {
						jTable0MouseMouseClicked(event);
					}
				});
			}
			return jTable0;
		}

		private JButton getJButton0() {
			if (jButton0 == null) {
				jButton0 = new JButton();
				jButton0.setIcon(new ImageIcon(getClass().getResource("/icones/zoom.png")));
				jButton0.setText("Pesquisar Por CPF");
				jButton0.addActionListener(new ActionListener() {
		
					public void actionPerformed(ActionEvent event) {
						jButton0ActionActionPerformed(event);
					}
				});
			}
			return jButton0;
		}

		private static void installLnF() {
                try {
                } catch (Exception e) {
                        System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
                                        + " on this platform:" + e.getMessage());
                }
        }

        /**
         * Main entry of the class.
         * Note: This class is only created so that you can easily preview the result at runtime.
         * It is not expected to be managed by the designer.
         * You can modify it as you like.
         */
        public static void main(String[] args) {
                installLnF();
                SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                                TabelaPesquisaCliente frame = new TabelaPesquisaCliente();
                                frame.setDefaultCloseOperation(TabelaPesquisaCliente.EXIT_ON_CLOSE);
                                frame.setTitle("TabelaPesquisaCliente");
                                frame.getContentPane().setPreferredSize(frame.getSize());
                                frame.pack();
                                frame.setLocationRelativeTo(null);
                                frame.setVisible(true);
                        }
                });
        }

        private void jButton2ActionActionPerformed(ActionEvent event) {
                String pesqcpf = JOptionPane.showInputDialog("Digite o cpf : ");
                try {
                if(pesqcpf == null || pesqcpf.trim().equals("")){
                }else{
                	FachadaCliente fach = new FachadaCliente();
                Collection<Cliente> colcli = fach.pesqclitodos(pesqcpf);
                if(colcli.size() >= 1){

                    Object[] colunas = {"nome","cpf","identidade","e-mail","telefone","endereco","numero","bairro","cidade","cep"};
                    
                    Object[][] linha = new String[colcli.size()][10];
                    
                	int carregando=0;
                    for(Cliente pessoa : colcli){
                            linha[carregando][0] = pessoa.getNomeCliente();
                            linha[carregando][1] = pessoa.getCpf();
                            linha[carregando][2] = pessoa.getIdentidade();
                            linha[carregando][3] = pessoa.getEmail();
                            linha[carregando][4] = pessoa.getTelefone();
                            linha[carregando][5] = pessoa.getEndereco().getLogradouro();
                            linha[carregando][6] = pessoa.getEndereco().getNumero();
                            linha[carregando][7] = pessoa.getEndereco().getBairro();
                            linha[carregando][8] = pessoa.getEndereco().getCidade();
                            linha[carregando][9] = pessoa.getEndereco().getCep();
                            carregando++;
                    }
                    
            jTable0.setModel(new DefaultTableModel(linha, colunas) {
            
                                    private static final long serialVersionUID = 1L;
                                    Class<?>[] types = new Class<?>[] { Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, };
            
                                    public Class<?> getColumnClass(int columnIndex) {
                                            return types[columnIndex];
                                    }
                            });
                	System.out.println("mais de 1");
                }else{
                	System.out.println("menos de 1");
                }
                }
                } catch (ClassNotFoundException e) {
                        // TODO Auto-generated catch block
                        JOptionPane.showMessageDialog(null, e.getMessage());
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        JOptionPane.showMessageDialog(null, "pessoa nao cadastrada");
                }
        }
        
        private void listando() throws ClassNotFoundException, SQLException{
                FachadaCliente fach = new FachadaCliente();
                
                Collection<Cliente> colcli = fach.Pesqtudo();
                
                Object[] colunas = {"nome","cpf","identidade","e-mail","telefone","endereco","numero","bairro","cidade","cep"};
                
                Object[][] linha = new String[colcli.size()][10];
                
                int carregando=0;
                for(Cliente pessoa : colcli){
                        linha[carregando][0] = pessoa.getNomeCliente();
                        linha[carregando][1] = pessoa.getCpf();
                        linha[carregando][2] = pessoa.getIdentidade();
                        linha[carregando][3] = pessoa.getEmail();
                        linha[carregando][4] = pessoa.getTelefone();
                        linha[carregando][5] = pessoa.getEndereco().getLogradouro();
                        linha[carregando][6] = pessoa.getEndereco().getNumero();
                        linha[carregando][7] = pessoa.getEndereco().getBairro();
                        linha[carregando][8] = pessoa.getEndereco().getCidade();
                        linha[carregando][9] = pessoa.getEndereco().getCep();
                        carregando++;
                }
                
        jTable0.setModel(new DefaultTableModel(linha, colunas) {
        
                                private static final long serialVersionUID = 1L;
                                Class<?>[] types = new Class<?>[] { Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, Object.class, };
        
                                public Class<?> getColumnClass(int columnIndex) {
                                        return types[columnIndex];
                                }
                        });
        }
        

        private void jButton1ActionActionPerformed(ActionEvent event) throws ClassNotFoundException, SQLException {
                listando();
        }

		private void jButton0ActionActionPerformed(ActionEvent event) {
			try {
				FachadaCliente fach = new FachadaCliente();
		String pesq = JOptionPane.showInputDialog("digite o CPF");
				Cliente cl = fach.PesquisarCliente(pesq);
				FormCadastroCliente fcc = new FormCadastroCliente(cl);
				fcc.setVisible(true);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (PessoaNaoEncontradaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExceptionCPFInvalido e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

		private void jTable0MouseMouseClicked(MouseEvent event){
			int linha = jTable0.getSelectedRow();
			int coluna = 1;
			String texto = jTable0.getValueAt(linha, coluna)+"";
			FachadaCliente fach = new FachadaCliente();
			try {
				Cliente pessoa = fach.pesqcpfponto(texto);
				FormCadastroCliente form = new FormCadastroCliente(pessoa);
				form.setVisible(true);
			} catch (PessoaNaoEncontradaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

}